<template>
  <div class="main-content">
    <haz-tree @selected="categoryCheckHandler" :is-edit="true" @downTemplateHandler="downTemplateHandler"/>
    <div style="flex: 1">
      <el-card shadow="never">
        <div class="ha-top">
              <div class="radio-t">
                <el-radio-group v-model="models.selectFormModel.status" size="mini" @change="statusChangeHandler">
                  <el-radio-button label="">全部</el-radio-button>
                  <el-radio-button label="0">待填报</el-radio-button>
                  <el-radio-button label="1">已填报</el-radio-button>
                  <el-radio-button label="2">已驳回</el-radio-button>
                </el-radio-group>
              </div>
              <div class="radio-t">
              <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="handleAdd"
                            >新增</el-button>
              <el-button type="primary" icon="el-icon-document" size="mini" plain @click="handleAddExcel"
                            >清单导入</el-button>
              <el-button type="primary" icon="el-icon-document-add" size="mini" plain @click="handleAddOcrExcel"
                            >扫描导入</el-button>
              <el-button type="primary" icon="el-icon-download" size="mini" plain @click="handleDownExcel"
                             >清单下载</el-button>
              <el-button type="primary" icon="el-icon-s-data" size="mini" plain @click="handleDiffData"
                             >数据对比</el-button>
              <!-- <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="handleDataIndex"
              >指标查看</el-button> -->
               <el-button type="primary" icon="el-icon-delete" size="mini" plain @click="handleCecycle"
                             >回收站</el-button>
              </div>
         
        </div>
        <div class="ha-top">
          <div class="radio-t">
            <el-input
                  placeholder="名称搜索"
                  size="mini"
                  v-model="models.selectFormModel.code"
                  @keyup.enter="nameSearchHandler"
                  @input="debouncedHandleSearch"
                  >
                  <i slot="suffix" class="el-input__icon el-icon-search" ></i>
            </el-input>
            </div>
            <div class="radio-t">
              <el-button type="primary" icon="el-icon-minus" size="mini" plain @click="handleBatchDel"
              >批量删除</el-button>
             <el-button type="primary" icon="el-icon-upload" size="mini" plain @click="handleBatchSubmit"
            >批量提交</el-button>
            </div>
          </div>
        <template v-if="columns && columns.length > 0">
            <dynamic-data-table ref="dataTable"
                :api="getTableData"
                :options="options"
                :columns="columns"
                :operates="operates"
                :query="models.selectFormModel"
                @handle-selection-change="handleSelectionChange"/>
          </template>
        <el-empty v-else/>
      </el-card>
    </div>
    <file-upload-dialog :options="uploadOptions" />
    <file-upload-dialog :options="ocrUploadOptions" @uploadSuccess="uploadSuccessHandler" />
    <common-dialog :options="exportOptions"  ref="exportDialog" @downloadHandler="downloadHandler"/>
  </div>

</template>

<script lang="ts">
import {Component, Vue,Ref} from 'vue-property-decorator';
import HazTree from "@/views/quality/components/HazTree.vue";
import NTitle from "@/components/NTitle.vue";
import {toReport,backReport,removeDataCommon,downloadData} from '@/api/investDataCommon'
import DynamicDataTable from '@/components/DataTable/DynamicDataTable.vue';
import { getCommonTitle,getDataList } from '@/api/dataSearch'
import { downloadPdf} from '@/api/investStructure'
import FileUploadDialog from '@/components/FileUploadDialog.vue';
import CommonDialog from '@/views/quality/components/CommonDialog.vue';

import _ from 'lodash'
@Component({
  methods: {},
  components: {NTitle, HazTree,DynamicDataTable,FileUploadDialog,CommonDialog}
})
export default class dataUpdate extends Vue {

  @Ref("dataTable") dataTable!:any;
  @Ref("exportDialog") exportDialog!:any;
  private getTableData = getDataList;
  columns: any =[];
  selectData:any;
  debouncedHandleSearch:any;
  uploadOptions:any={
     title:'清单导入',
     dialogVisible:false,
     workId:'',
     backendVerify:true,
     alertTitle:'只能上传xls/xlsx文件',
     structureId:'',

     categoryId:'',
     url:'/bus/structure/importRecord',
  }

  exportOptions:any={
     title:'',
     dialogVisible:false,
     workId:'',
     backendVerify:true,
     structureId:''
  }

  ocrUploadOptions:any={
     title:'OCR识别导入',
     dialogVisible:false,
     workId:'',
     structureId:'',
     alertTitle:'ORC识别PDF文件，请选择pdf文件',
     backendVerify:false,
     categoryId:'',
     url:'/bus/structure/importPdf',
  }

  models:any={
        category:{
            filterText: '',
            data: [],
            defaultProps: {
              children: 'children',
              label: 'label'
            }
        },
        selectFormModel:{
            id: '',
            structureId:'',
            categoryId:'',
            bigCategoryId:'',
            midCategoryId:'',
            workId:'',
            polygon:'0',
            status:'',
            code:'',
            createBy:'',
            originId:'',
            workName:'',
            categoryName:''
        },
        upload:{
            id: '',
            force: '',
            workId:'',
            departId:'',
            areaId:'',
            workName:'',
            categoryName:''
        }
    };
  // table 的参数
  options: any = {
    stripe: true, // 是否为斑马纹 table
    loading: false, // 是否添加表格loading加载动画
    highlightCurrentRow: true, // 是否支持当前行高亮显示
    multipleSelect: true, // 是否支持列表项选中功能
  };


  //按钮操作组
  operates: any = {
        width: 200,
        fixed: 'right',
        list: [
            {
               // label: '查看',
                type: 'primary',
                icon: 'el-icon-search',
                disabled: () => {
                    return false;
                },
                permission: 'bus:data:view',
                method: (index, row) => {
                    this.handleView(index, row);
                },
                plain:true,
                tooltip:'查看调查对象'
            },
            {
               // label: '查看',
                type: 'primary',
                icon: 'el-icon-edit',
                disabled: () => {
                    return false;
                },
                visibled: (index, row) => {
                   return row.status === '0' || row.status ==='2';
                },
                permission: 'bus:data:view',
                method: (index, row) => {
                    this.handleEdit(index, row);
                },
                plain:true,
                tooltip:'编辑数据'
            },
            {
               // label: '查看',
                type: 'primary',
                icon: 'el-icon-picture-outline',
                disabled: () => {
                    return false;
                },
                visibled: (index, row) => {
                   return row.reportType === '2';
                },
                permission: 'bus:data:view',
                method: (index, row) => {
                    this.handleDiff(index, row);
                },
                plain:true,
                tooltip:'数据比对'
            },
            {
               // label: '导出',
                type: 'primary',
                icon: 'el-icon-download',
                show: true,
                disabled: () => {
                    return false;
                },
                visibled: (index, row) => {
                   return row.status === '1';
                },
                permission: 'bus:data:view',
                method: (index, row) => {
                    this.handleDown(index, row);
                },
                plain:true,
                tooltip:'导出调查对象WORD文档'
            },
            {
             //   label: '上报',
                type: 'primary',
                icon: 'el-icon-upload',
                permission: 'bus:data:view',
                show: true,
                visibled: (index, row) => {
                   return row.status === '0';
                },
                disabled: () => {
                    return false;
                },
                method: (index, row) => {
                    this.toReportHandler(index, row);
                },
                plain:true,
                 tooltip:'数据提交'
            },
            {
             //   label: '上报',
                type: 'primary',
                icon: 'el-icon-refresh-left',
                permission: 'bus:data:view',
                show: true,
                visibled: (index, row) => {
                   return row.status == '1';
                },
                disabled: () => {
                    return false;
                },

                method: (index, row) => {
                    this.backReportHandler(index, row);
                },
                plain:true,
                tooltip:'撤回上报'
            },
            {
                type: 'primary',
                icon: 'el-icon-delete',
                show: true,
                permission: 'bus:data:view',
                visibled: (index, row) => {
                   return row.status == '0';
                },
                disabled: () => {
                    return false;
                },
                method: (index, row) => {
                    this.handleBatchDelete(row);
                },
                plain:true,
                tooltip:'删除数据'
            }
        ]
    };

    get elTableRef() {
      return this.dataTable;
    }

    downTemplateHandler(item){
      const level = item.extra.level;
      let model:any= null;
      switch(level){
          case 0:
              model ={workId: item.id};
          break;
          case 1:
              model ={categoryId: item.id,workId:item.children[0].children[0].extra.rootId};
            break;
          case 2:
              model ={categoryId: item.id,workId:item.children[0].extra.rootId};
              break;
          case 3:
              model ={structureId: item.code,workId:item.extra.rootId};
            break;
      }
      downloadPdf(model).then(res => {
      if (res && res.data) {
          (this as any).$download(res.data.fileName);
        }
      }).catch((e) => {
        console.error(e);
      });
    }

    handleBatchDel(){
      
      if(!this.selectData || this.selectData == undefined || this.selectData.length == 0){
        this.$message.info("请选择数据然后才能批量操作");
        return;
      }
      if(this.selectData.every(item => item.status === '0')){

        const ids = this.selectData.map(d => d.id);
        this.$confirm('确定要删除选定数据吗？', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            return removeDataCommon({ 'ids':ids});
          }).then((response: any) => {
            this.dataTable.refresh();
            this.$message.success(response.msg);
          }).catch((e) => {
            console.error(e);
          });
      }else{
        this.$message.info("部分数据不能删除，已经去掉不能删除的数据，请检查后再次点击删除");
        const  dt = this.selectData.filter(d =>d.status !== '0');

        dt.forEach(row =>{
          this.dataTable.toggleUnSelection(row)
        })
        
      }

    }

    handleBatchSubmit(){
      console.log(1)
    }

    handleBatchDelete(row) {
    //删除
      this.$confirm('确定要删除选定数据吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return removeDataCommon({ 'ids': [row.id] });
      }).then((response: any) => {
        this.dataTable.refresh();
        this.$message.success(response.msg);
      }).catch((e) => {
        console.error(e);
      });
  }

  handleSelectionChange(val): void {

    this.selectData = val;
  }

  getTitle(structureId?){
    if(structureId){
      getCommonTitle({id:structureId}).then(res =>{
        this.columns = res.data;
        if(this.dataTable){
            this.dataTable.refresh();
        }
      })
    }else{
      getCommonTitle().then(res =>{
        this.columns = res.data;
        if(this.dataTable){
            this.dataTable.refresh();
        }
      })
    }
   
  }

  nameSearchHandler(){
    this.models.selectFormModel.code =  this.models.selectFormModel.code.trim();
    this.dataTable.refresh();
  }

  handleCecycle(){
    this.$router.push('/quality/recycle');
  }

  handleAddOcrExcel(){
    if(!this.models.upload.id){
        this.$message("请选择类别");
        return;
    }
    this.ocrUploadOptions.dialogVisible = true;
  }

  handleDownExcel(){
    if(!this.models.upload.id){
        this.$message("请选择类别");
        return;
    }
    this.exportOptions.dialogVisible = true;
    this.exportDialog.exportParamProcess();
   
  }

  downloadHandler(models:any){
    if(models){
      const dataProps = {
        common:{
          head: models.common.headOptions.checkedValues,
          code: models.common.codeOptions.checkedValues,
          end:  models.common.endOptions.checkedValues
        },
        commonExt:{
          head:models.commonExt.headOptions.checkedValues,
          code:models.commonExt.codeOptions.checkedValues,
          end:models.commonExt.endOptions.checkedValues
        },
        dynamic:{
          head:models.dynamic.headOptions.checkedValues,
          code:models.dynamic.codeOptions.checkedValues,
          end:models.dynamic.endOptions.checkedValues
        },
      };
      this.models.selectFormModel.dataProps = dataProps;
    }
     
    this.downExcel();
  }

  downExcel(){
    downloadData(this.models.selectFormModel).then(res => {
      if (res && res.data) {
        (this as any).$download(res.data.fileName);
      }
    }).catch((e) => {
      console.error(e);
    });
  }

  statusChangeHandler(val){
    this.dataTable.refresh();
  }

  toReportHandler(index,row){
    toReport({id: row.id}).then(res=>{
      this.dataTable.refresh();
    })
  }

  uploadSuccessHandler(val){
    this.models.selectFormModel.id=val.data;
    this.$router.push({ name: '数据新增OCR', params: this.models.selectFormModel});

  }
  backReportHandler(index,row){
    backReport({id: row.id}).then(res=>{
      this.dataTable.refresh();
    })
  }
  handleView(index: number, row: any) {

       this.$router.push({ path: '/quality/surveyView', query: { dataId: row.id, structureId: row.structureId}});
   }

   handleDiff(index: number, row: any){
    this.models.selectFormModel.id = row.id;
    this.models.selectFormModel.structrueId = row.structureId;
    this.models.selectFormModel.areaId = row.areaId;
    this.$router.push({ name: '数据新增OCR', params:this.models.selectFormModel});
   }

   handleEdit(index: number, row: any) {
      this.models.selectFormModel.id = row.id;
      this.$router.push({ path: '/quality/surveyAdd', query: this.models.selectFormModel});
  }
  handleDiffData(){
    if(!this.selectData){
      this.$message.error("请选择数据");
      return;
    }
    if(this.selectData.length < 2){
      this.$message.error("至少选择两个数据");
      return;
    }
    const dt1 = this.selectData[0].id;
    const dt2 = this.selectData[1].id;

    this.$router.push({ path: '/quality/dataDiff', query: {dataId:dt1,historyDataId:dt2,structureId:this.models.selectFormModel.structureId }});
  }

  handleDataIndex(){
    const dt1 = this.selectData[0].id;
    this.$router.push({ path: '/quality/indexView', query: {dataId:dt1,structureId:this.selectData[0].structureId }});
  }

  handleAdd(){
    if(!this.models.upload.id){
        this.$message("请选择类别");
        return;
    }
    this.models.selectFormModel.id = null;
    this.$router.push({ path: '/quality/surveyAdd', query: this.models.selectFormModel});
  }

  handleAddExcel(){
    if(!this.models.upload.id){
        this.$message("请选择类别");
        return;
    }
    this.uploadOptions.dialogVisible = true;
  }

  handleDown(index: number, row: any) {

    downloadPdf({id:row.id,structureId: row.structureId}).then(res => {
      if (res && res.data) {
          (this as any).$download(res.data.fileName);
      }
    }).catch((e) => {
      console.error(e);
    });
}

  categoryCheckHandler(data){
  
    const {code, level, rootId, rootName, polygon} = data.extra;
    this.models.selectFormModel.workId =  rootId;
    if(code){
        this.getTitle(code);
        this.models.upload.categoryName = data.label;
        this.uploadOptions.workId = rootId;
        this.models.selectFormModel = {
            ...this.models.selectFormModel, 
            categoryId: data.id,
            structureId: code,
            polygon: polygon,
            workName: rootName,
            categoryName: data.label,
        };

        this.models.upload ={
          ...this.models.upload,
          workId: rootId,
          id: code,
          workName: rootName
        }
        this.uploadOptions.categoryId = data.id;
        this.uploadOptions.structureId = code;
        this.exportOptions.structureId= code;

        this.ocrUploadOptions = {
            ...this.ocrUploadOptions,
            workId: rootId,
            categoryId: data.id,
            structureId: code
        };
    }else{
       this.getTitle();
        this.models.upload.id=null;
        this.models.selectFormModel.structureId = null;
        switch(level){
          case 2:
              this.models.selectFormModel.midCategoryId =data.id;
              this.models.selectFormModel.bigCategoryId= null;
              this.models.selectFormModel.categoryId = null;
            break;
          case 1:
              this.models.selectFormModel.bigCategoryId =data.id;
              this.models.selectFormModel.categoryId = null;
              this.models.selectFormModel.midCategoryId =null;
            break;
          default:
              this.models.selectFormModel.bigCategoryId =null;
              this.models.selectFormModel.categoryId = null;
              this.models.selectFormModel.midCategoryId =null;
            break;
        }
    }
  }
  created(){
    this.debouncedHandleSearch = _.debounce(this.nameSearchHandler, 500);
  }
}
</script>
<style lang="scss" scoped>

::v-deep .el-card__header {
  padding: 0px 6px;
}

::v-deep .el-card__body{
  padding: 6px 6px 0px 6px;
}
</style>
